var fs = require('fs');
var imgsize = require('image-size')
var d = new Date()
var logs = ''

// 设置图片大小限制
var minWidth = 0
var minHeight = 1100
// 设置宽高比类型
var ratio = 1
// 0: 无限制
// 1: 宽比高长
// 2: 高比宽长

viewdir('./in/', (files) => {
    for (let i = 0; i < files.length; i++) {
        try {
            let is = imgsize('./in/' + files[i])
            if (is.height >= minHeight && is.width >= minWidth) {
                switch (ratio) {
                    case 0:
                        fileHandle(files[i], is.height, is.width)
                        break
                    case 1:
                        if (is.width > is.height) {
                            fileHandle(files[i], is.height, is.width)
                        }
                        break
                    case 2:
                        if (is.width < is.height) {
                            fileHandle(files[i], is.height, is.width)
                        }
                        break
                    default:
                        break
                }

            }

        } catch (e) {
            console.log(e)
        }
    }
    creatLog()
})

//文件处理
function fileHandle(path, height, width) {
    console.log(path + ' ' + width + 'x' + height)
    fs.cp('./in/' + path, './out/' + path, (err) => {
        if (err) {
            console.log(err)
        }
    })
    let t = path + '  ' + height + 'x' + width + '\n'
    logs = logs + t
}

// 日志
function creatLog() {
    fs.appendFile('./log/' + d.getTime() + '.txt', logs, (err) => {
        if (err) {
            console.log(err)
        }
    })
    console.log('')
}

//查找目录下所有文件
function viewdir(path, cellback) {
    fs.readdir(path, (err, files) => {
        if (err) {
            console.log(err)
            cellback(false)
        } else {
            let size = 0
            for (let i = 0; i < files.length; i++) {
                size = size + fs.statSync(path + '/' + files[i]).size
            }
            cellback(files, size)
        }
    })
}